
// 任务管理器
class TaskManager {
  constructor() {
    this.tasks = [];
    this.currentTaskIndex = 0;
    this.isRunning = false;
    this.init();
  }

  async init() {
    await this.loadTasks();
    await this.loadProgress();
    this.renderUI();
    this.bindEvents();
  }

  async loadTasks() {
    const result = await chrome.storage.local.get(['tasks']);
    this.tasks = result.tasks || this.getDefaultTasks();
  }

  async loadProgress() {
    const result = await chrome.storage.local.get(['lastRunDate', 'completedTasks']);
    const today = new Date().toDateString();
    const lastRun = result.lastRunDate;
    
    if (lastRun === today) {
      this.completedTasks = result.completedTasks || [];
    } else {
      this.completedTasks = [];
    }
  }

  getDefaultTasks() {
    return [
      {
        id: 1,
        name: '打开邮箱',
        type: 'open-url',
        target: 'https://mail.google.com',
        value: ''
      },
      {
        id: 2,
        name: '打开工作面板',
        type: 'open-url',
        target: 'https://www.notion.so',
        value: ''
      }
    ];
  }

  renderUI() {
    this.renderStats();
    this.renderTaskList();
    this.updateExecuteButton();
  }

  renderStats() {
    const completedCount = this.completedTasks.length;
    const totalCount = this.tasks.length;
    
    document.getElementById('completed-count').textContent = completedCount;
    document.getElementById('total-count').textContent = totalCount;
  }

  renderTaskList() {
    const taskList = document.getElementById('task-list');
    taskList.innerHTML = '';

    this.tasks.forEach((task, index) => {
      const taskItem = document.createElement('div');
      taskItem.className = 'task-item';
      
      const isCompleted = this.completedTasks.includes(task.id);
      const isRunning = this.isRunning && index === this.currentTaskIndex;
      
      if (isCompleted) {
        taskItem.classList.add('completed');
      }
      if (isRunning) {
        taskItem.classList.add('running');
      }

      taskItem.innerHTML = `
        <span class="task-icon">${this.getTaskIcon(task.type)}</span>
        <span class="task-name">${task.name}</span>
        <span class="task-status ${isCompleted ? 'completed' : ''} ${isRunning ? 'running' : ''}">
          ${isCompleted ? '已完成' : isRunning ? '执行中' : '待执行'}
        </span>
      `;

      taskList.appendChild(taskItem);
    });
  }

  getTaskIcon(type) {
    const icons = {
      'open-url': '🌐',
      'fill-form': '📝',
      'click-element': '👆',
      'custom-script': '⚡'
    };
    return icons[type] || '📋';
  }

  updateExecuteButton() {
    const btn = document.getElementById('execute-btn');
    const allCompleted = this.completedTasks.length === this.tasks.length;
    
    if (allCompleted) {
      btn.innerHTML = '<span class="btn-icon">✅</span><span class="btn-text">今日已完成</span>';
      btn.disabled = true;
    } else if (this.isRunning) {
      btn.innerHTML = '<span class="btn-icon">⏳</span><span class="btn-text">执行中...</span>';
      btn.disabled = true;
    } else {
      btn.innerHTML = '<span class="btn-icon">🚀</span><span class="btn-text">开始今日任务</span>';
      btn.disabled = false;
    }
  }

  bindEvents() {
    document.getElementById('execute-btn').addEventListener('click', () => this.executeTasks());
    document.getElementById('settings-btn').addEventListener('click', () => this.openSettings());
    document.getElementById('reset-btn').addEventListener('click', () => this.resetProgress());
    document.getElementById('close-modal').addEventListener('click', () => this.closeSettings());
    document.getElementById('add-task').addEventListener('click', () => this.addTask());
    
    // 模态框外部点击关闭
    document.getElementById('settings-modal').addEventListener('click', (e) => {
      if (e.target.id === 'settings-modal') {
        this.closeSettings();
      }
    });
  }

  async executeTasks() {
    if (this.isRunning) return;
    
    this.isRunning = true;
    this.currentTaskIndex = 0;
    this.updateExecuteButton();
    this.showProgress();

    for (let i = 0; i < this.tasks.length; i++) {
      const task = this.tasks[i];
      
      if (this.completedTasks.includes(task.id)) {
        continue;
      }

      this.currentTaskIndex = i;
      this.renderTaskList();
      this.updateProgress();

      try {
        await this.executeTask(task);
        this.completedTasks.push(task.id);
        await this.saveProgress();
      } catch (error) {
        console.error(`任务执行失败: ${task.name}`, error);
        this.showNotification(`任务失败: ${task.name}`, 'error');
      }
    }

    this.isRunning = false;
    this.renderUI();
    this.hideProgress();
    this.showNotification('今日任务已完成！', 'success');
  }

  async executeTask(task) {
    console.log(`执行任务: ${task.name}`);
    
    switch (task.type) {
      case 'open-url':
        await this.openUrl(task.target);
        break;
      case 'fill-form':
        await this.fillForm(task.target, task.value);
        break;
      case 'click-element':
        await this.clickElement(task.target);
        break;
      case 'custom-script':
        await this.executeCustomScript(task.value);
        break;
      default:
        throw new Error(`未知的任务类型: ${task.type}`);
    }

    // 等待2秒让页面加载
    await this.delay(2000);
  }

  async openUrl(url) {
    await chrome.tabs.create({ url });
  }

  async fillForm(selector, value) {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: (selector, value) => {
        const element = document.querySelector(selector);
        if (element) {
          element.value = value;
          element.dispatchEvent(new Event('input', { bubbles: true }));
          element.dispatchEvent(new Event('change', { bubbles: true }));
        }
      },
      args: [selector, value]
    });
  }

  async clickElement(selector) {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: (selector) => {
        const element = document.querySelector(selector);
        if (element) {
          element.click();
        }
      },
      args: [selector]
    });
  }

  async executeCustomScript(script) {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: new Function(script)
    });
  }

  showProgress() {
    document.getElementById('progress-container').style.display = 'block';
    this.updateProgress();
  }

  hideProgress() {
    document.getElementById('progress-container').style.display = 'none';
  }

  updateProgress() {
    const completed = this.completedTasks.length;
    const total = this.tasks.length;
    const percentage = total > 0 ? (completed / total) * 100 : 0;
    
    document.getElementById('progress-fill').style.width = `${percentage}%`;
    document.getElementById('progress-text').textContent = `${completed}/${total}`;
  }

  async saveProgress() {
    const today = new Date().toDateString();
    await chrome.storage.local.set({
      lastRunDate: today,
      completedTasks: this.completedTasks
    });
  }

  async resetProgress() {
    if (confirm('确定要重置今日进度吗？')) {
      this.completedTasks = [];
      await chrome.storage.local.set({
        completedTasks: [],
        lastRunDate: ''
      });
      this.renderUI();
      this.showNotification('进度已重置', 'info');
    }
  }

  openSettings() {
    document.getElementById('settings-modal').style.display = 'flex';
    this.renderEditableTaskList();
  }

  closeSettings() {
    document.getElementById('settings-modal').style.display = 'none';
  }

  renderEditableTaskList() {
    const list = document.getElementById('editable-task-list');
    list.innerHTML = '';

    this.tasks.forEach(task => {
      const li = document.createElement('li');
      li.innerHTML = `
        <div class="task-info">
          <strong>${task.name}</strong>
          <small>${this.getTaskTypeLabel(task.type)} - ${task.target}</small>
        </div>
        <button class="delete-btn" onclick="taskManager.deleteTask(${task.id})">删除</button>
      `;
      list.appendChild(li);
    });
  }

  getTaskTypeLabel(type) {
    const labels = {
      'open-url': '打开网页',
      'fill-form': '填写表单',
      'click-element': '点击元素',
      'custom-script': '自定义脚本'
    };
    return labels[type] || type;
  }

  async addTask() {
    const type = document.getElementById('task-type').value;
    const name = document.getElementById('task-name').value.trim();
    const target = document.getElementById('task-target').value.trim();
    const value = document.getElementById('task-value').value.trim();

    if (!name || !target) {
      this.showNotification('请填写任务名称和目标', 'warning');
      return;
    }

    const newTask = {
      id: Date.now(),
      name,
      type,
      target,
      value
    };

    this.tasks.push(newTask);
    await this.saveTasks();
    this.renderEditableTaskList();
    this.renderUI();

    // 清空表单
    document.getElementById('task-name').value = '';
    document.getElementById('task-target').value = '';
    document.getElementById('task-value').value = '';

    this.showNotification('任务添加成功', 'success');
  }

  async deleteTask(taskId) {
    this.tasks = this.tasks.filter(task => task.id !== taskId);
    await this.saveTasks();
    this.renderEditableTaskList();
    this.renderUI();
    this.showNotification('任务删除成功', 'success');
  }

  async saveTasks() {
    await chrome.storage.local.set({ tasks: this.tasks });
  }

  showNotification(message, type = 'info') {
    // 简单的通知实现
    const notification = document.createElement('div');
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 12px 20px;
      border-radius: 6px;
      color: white;
      font-size: 14px;
      z-index: 10000;
      transition: all 0.3s ease;
      max-width: 300px;
      word-wrap: break-word;
    `;

    const colors = {
      success: '#28a745',
      error: '#dc3545',
      warning: '#ffc107',
      info: '#17a2b8'
    };

    notification.style.backgroundColor = colors[type] || colors.info;
    notification.textContent = message;

    document.body.appendChild(notification);

    setTimeout(() => {
      notification.style.opacity = '0';
      notification.style.transform = 'translateX(100%)';
      setTimeout(() => {
        if (notification.parentNode) {
          notification.parentNode.removeChild(notification);
        }
      }, 300);
    }, 3000);
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// 初始化任务管理器
const taskManager = new TaskManager();
